// app.js
// 导入工具类
const { wordDataManager, reviewScheduler, magicCoinManager, audioManager, wordLearningDataManager, challengeDataManager, dictationManager, cloudManager, storageManager, aiManager } = require('./manager/index');
// 导入云配置常量
const { CLOUD_ENV_ID } = require('./utils/cloudConfig');
// 导入词书相关常量和工具
const { BOOKS_DOWNLOAD_TIMESTAMP_KEY, BUILTIN_BOOKS_CACHE_KEY, clearCache } = require('./utils/builtinBooks');

App({
  onLaunch() {
    // 初始化云开发环境
    if (wx.cloud) {
      wx.cloud.init({
        env: CLOUD_ENV_ID, // 使用云配置常量中的环境ID
        traceUser: true,
      });
      console.log('云开发环境初始化成功');
    } else {
      console.warn('当前微信版本不支持云开发');
    }

    // 初始化全局工具类实例
    this.initGlobalInstances();

    // 加载应用配置
    this.loadAppConfig().then(() => {
      // 初始化AI管理器
      this.globalData.aiManager.initialize();
    });

    // 检查词书索引文件下载时间，超过半小时则清除缓存
    this.checkAndClearBooksCache();

    // 检查缓存空间是否即将耗尽
    this.checkStorageSpace();

    // 登录
    this.login();
  },

  /**
   * 加载应用配置
   */
  loadAppConfig() {
    return this.globalData.cloudManager.getData('AppConfig', { type: 'system' }).then(res => {
      if (res.data.length > 0) {
        this.globalData.appConfig = res.data[0];
      }
    });
  },
  
  /**
   * 检查词书索引文件下载时间，超过半小时则清除缓存
   */
  checkAndClearBooksCache() {
    try {
      // 获取词书索引文件下载时间戳
      const storageManager = this.getStorageManager();
      const downloadTimestamp = storageManager.getStorage(BOOKS_DOWNLOAD_TIMESTAMP_KEY);
      
      // 如果存在下载时间戳
      if (downloadTimestamp) {
        const now = Date.now();
        const halfHourInMs = 30 * 60 * 1000; // 半小时的毫秒数
        
        // 检查是否超过半小时
        if (now - downloadTimestamp > halfHourInMs) {
          console.log('词书索引文件下载时间已超过半小时，清除缓存');
          clearCache();
        } else {
          console.log('词书索引文件缓存有效');
        }
      } else {
        console.log('未找到词书索引文件下载时间戳');
      }
    } catch (error) {
      console.error('检查词书缓存时发生错误:', error);
    }
  },

  onShow() {
    // 每次应用启动或从后台进入前台时触发
    console.log('应用显示');
  },

  onHide() {
    // 应用从前台进入后台时触发
    console.log('应用隐藏');
    // 保存学习数据到云数据库
    this.saveAllLearningDataToCloud();
  },
  
  onUnload() {
    // 页面卸载时触发
    console.log('页面卸载');
    // 保存学习数据到云数据库
    this.saveAllLearningDataToCloud();
  },
  
  /**
   * 保存用户数据到云数据库
   */
  saveAllLearningDataToCloud() {
    // 确保用户已登录且有openid
    if (!this.globalData.openid) {
      console.log('用户未登录，无法保存数据到云数据库');
      return;
    }
    
    try {
      // 获取单词学习数据管理器实例
      const wordLearningDataManager = this.getWordLearningDataManager();
      // 获取所有学习数据
      const wordLearningInfoData = wordLearningDataManager.getAllLearningData();
      
      // 获取其他缓存数据
      const storageManager = this.getStorageManager();
      const learningData = storageManager.getStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, {});
      const userSettings = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_SETTINGS, {});
      const todayTaskData = storageManager.getStorage(storageManager.STORAGE_KEYS.TODAY_TASK_DATA, {});
      const userChallengeStats = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_CHALLENGE_STATS, {});
      const userMagicCoins = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_MAGIC_COINS, {});
      const userChallengeRecords = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_CHALLENGE_RECORDS, {});
      
      console.log('准备保存数据到云数据库');
      console.log('- wordLearningInfoData:', Object.keys(wordLearningInfoData).length, '条记录');
      console.log('- learningData:', Object.keys(learningData).length, '条记录');
      console.log('- userSettings:', Object.keys(userSettings).length, '条记录');
      console.log('- todayTaskData:', Object.keys(todayTaskData).length, '条记录');
      console.log('- userChallengeStats:', Object.keys(userChallengeStats).length, '条记录');
      console.log('- userMagicCoins:', JSON.stringify(userMagicCoins));
      console.log('- userChallengeRecords:', Object.keys(userChallengeRecords).length, '条记录');
      
      // 准备更新数据
      const userInfo = {
        wordLearningInfoData: wordLearningInfoData,
        learningData: learningData,
        userSettings: userSettings,
        todayTaskData: todayTaskData,
        userChallengeStats: userChallengeStats,
        userMagicCoins: userMagicCoins,
        userChallengeRecords: userChallengeRecords
      };
      
      // 调用云函数更新用户信息
      wx.cloud.callFunction({
        name: 'updateUser',
        data: { userInfo },
        success: res => {
          console.log('学习数据保存到云数据库成功', res);
        },
        fail: err => {
          console.error('学习数据保存到云数据库失败', err);
        }
      });
    } catch (error) {
      console.error('保存学习数据到云数据库时发生错误', error);
    }
  },

  // 初始化应用数据
  initAppData() {
    // 检查并初始化学习数据
    this.initLearningData();
    
    // 检查并初始化用户设置
    this.initUserSettings();
  },

  // 初始化学习数据
  initLearningData() {
    const storageManager = this.getStorageManager();
    let learningData = storageManager.getStorage(storageManager.STORAGE_KEYS.LEARNING_DATA);
    if (!learningData) {
      learningData = {
        totalWordsLearned: 0,
        learningDays: 0,
        medalsCount: 0,
        lastStudyDate: '',
        consecutiveDays: 0,
        vocabulary: {
          currentWordIndex: 1,
          totalWordsCount: 0,
          unitName: '单元学习'
        }
      };
      storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, learningData);
    } else {
      // 确保vocabulary对象存在
      if (!learningData.vocabulary) {
        learningData.vocabulary = {
          currentWordIndex: 1,
          totalWordsCount: 0,
          unitName: '单元学习'
        };
        storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, learningData);
      }
    }
    this.globalData.learningData = learningData;
  },

  // 初始化用户设置
  initUserSettings() {
    const storageManager = this.getStorageManager();
    let userSettings = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_SETTINGS);
    if (!userSettings) {
      userSettings = {
        dailyTimeLimit: 30, // 分钟
        learningDifficulty: 'easy', // easy, medium, hard
        notificationsEnabled: true,
        soundEnabled: true,
        vibrationEnabled: true
      };
      storageManager.setStorage(storageManager.STORAGE_KEYS.USER_SETTINGS, userSettings);
    }
    this.globalData.userSettings = userSettings;
  },

  // 更新学习数据
  updateLearningData(data) {
    const storageManager = this.getStorageManager();
    let learningData = storageManager.getStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, {});
    learningData = { ...learningData, ...data };
    storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, learningData);
    this.globalData.learningData = learningData;
  },

  // 更新用户设置
  updateUserSettings(settings) {
    const storageManager = this.getStorageManager();
    let userSettings = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_SETTINGS, {});
    userSettings = { ...userSettings, ...settings };
    storageManager.setStorage(storageManager.STORAGE_KEYS.USER_SETTINGS, userSettings);
    this.globalData.userSettings = userSettings;
  },

  updateUserInfoInGlobal(userInfo) {
    this.globalData.userInfo = userInfo;
  },

  // 登录方法 - 使用云函数登录
  login() {
    const that = this;
    wx.showLoading({ title: '登录中...' });
    
    // 调用云函数login
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        console.log('云函数登录成功', res.result);
        const { openid, userInfo, isNewUser } = res.result;
        
        // 保存用户信息到全局
        that.globalData.openid = openid;
        if (userInfo) {
          that.globalData.userInfo = userInfo;
          this.globalData.storageManager.setStorage(this.globalData.storageManager.STORAGE_KEYS.USER_INFO, {
            nickname: userInfo.nickname,
            avatar: userInfo.avatar,
            gender: userInfo.gender,
            country: userInfo.country,
            province: userInfo.province,
            city: userInfo.city
          });
        }
        
        // 如果是新用户，可以进行初始化操作
        if (isNewUser) {
          console.log('新用户登录，进行初始化');
        }
        
        // 登录成功后，尝试从云数据库加载学习数据
        that.loadWordLearningDataFromCloud();
      },
      fail: err => {
        console.error('云函数登录失败', err);
        // 失败时回退到本地存储的登录方式
        this.localLogin();
      },
      complete: () => {
        wx.hideLoading();
        // 初始化应用数据
        this.initAppData();
      }
    });
  },
  
  // 本地登录回退方法
  localLogin() {
    wx.login({
      success: res => {
        console.log('本地登录成功，获取到code:', res.code);
        // 可以在这里保存code，后续尝试重新调用云函数
      },
      fail: err => {
        console.error('本地登录失败', err);
      }
    });
  },
  
  // 更新云数据库中的用户信息
  updateUserInfoInCloud(userInfo) {
    wx.cloud.callFunction({
      name: 'updateUser',
      data: {
        userInfo: {
          nickname: userInfo.nickName,
          avatar: userInfo.avatarUrl,
          gender: userInfo.gender
        }
      },
      success: res => {
        console.log('云数据库用户信息更新成功', res);
      },
      fail: err => {
        console.error('云数据库用户信息更新失败', err);
      }
    });
  },

  // 初始化全局工具类实例
  initGlobalInstances() {
    // 初始化并存储工具类实例
    
    // 先初始化云管理器，因为其他管理器可能会用到
    this.globalData.cloudManager = cloudManager.getInstance();

    // 1. 首先初始化wordLearningDataManager，因为它被其他管理器依赖
    this.globalData.wordLearningDataManager = wordLearningDataManager();
    
    // 2. 初始化wordDataManager，并传入wordLearningDataManager实例进行初始化
    this.globalData.wordDataManager = wordDataManager();
    this.globalData.wordDataManager.initialize(this.globalData.wordLearningDataManager);
    
    // 3. 初始化存储管理器
    this.globalData.storageManager = storageManager();
    
    // 4. 初始化其他管理器
    this.globalData.reviewScheduler = reviewScheduler();
    this.globalData.reviewScheduler.initialize(this.globalData.wordLearningDataManager, this.globalData.wordDataManager);
    this.globalData.magicCoinManager = magicCoinManager();
    this.globalData.audioManager = audioManager();
    this.globalData.challengeDataManager = challengeDataManager();
    this.globalData.dictationManager = dictationManager();
    this.globalData.dictationManager.initialize(this.globalData.wordDataManager, this.globalData.reviewScheduler, this.globalData.audioManager);
    this.globalData.aiManager = aiManager();
  },
  
  // 获取WordDataManager实例
  getWordDataManager() {
    return this.globalData.wordDataManager;
  },
  
  // 获取ReviewScheduler实例
  getReviewScheduler() {
    return this.globalData.reviewScheduler;
  },
  
  // 获取MagicCoinManager实例
  getMagicCoinManager() {
    return this.globalData.magicCoinManager;
  },
  
  // 获取AudioManager实例
  getAudioManager() {
    return this.globalData.audioManager;
  },
  
  // 获取WordLearningDataManager实例
  getWordLearningDataManager() {
    return this.globalData.wordLearningDataManager;
  },
  
  // 获取ChallengeDataManager实例
  
  /**
   * 从云数据库加载单词学习数据
   */
  loadWordLearningDataFromCloud() {
    // 确保用户已登录且有openid
    if (!this.globalData.openid) {
      console.log('用户未登录，无法从云数据库加载学习数据');
      return;
    }
    
    // 确保wordLearningDataManager已初始化
    if (!this.globalData.wordLearningDataManager) {
      console.log('wordLearningDataManager未初始化');
      return;
    }
    
    // 获取本地缓存中的学习数据
    const wordLearningDataManager = this.getWordLearningDataManager();
    const localData = wordLearningDataManager.getAllLearningData();
    
    // 如果本地缓存为空，从云数据库获取
    if (Object.keys(localData).length === 0) {
      console.log('本地缓存中没有学习数据，从云数据库获取');
      
      // 调用云函数获取用户数据，查询所有需要的字段
      wx.cloud.callFunction({
        name: 'getData',
        data: {
          collection: 'User',
          query: { openid: this.globalData.openid },
          projection: { 
            wordLearningInfoData: 1,
            learningData: 1,
            userSettings: 1,
            todayTaskData: 1,
            userChallengeStats: 1,
            userMagicCoins: 1,
            userChallengeRecords: 1
          }
        },
        success: res => {
          console.log('从云数据库获取用户数据成功', res);
          if (res.result && res.result.data && res.result.data.length > 0) {
            const userData = res.result.data[0];
            
            // 保存wordLearningInfoData到学习数据管理器
            if (userData.wordLearningInfoData && typeof userData.wordLearningInfoData === 'object') {
              console.log('获取到云数据库中的wordLearningInfoData，共', Object.keys(userData.wordLearningInfoData).length, '条记录');
              wordLearningDataManager._saveAllLearningData(userData.wordLearningInfoData);
            }
            
            // 保存其他数据到本地缓存
            const storageManager = this.getStorageManager();

            storageManager.setStorage(storageManager.STORAGE_KEYS.USER_INFO, {
              avatar: userData.avatar || '',
              nickname: userData.nickname || '',
              gender: userData.gender || 0,
              country: userData.country || '',
              province: userData.province || '',
              city: userData.city || '',
              callAICount: userData.callAICount || 0
            });
            
            if (userData.learningData && typeof userData.learningData === 'object') {
              console.log('获取到云数据库中的learningData，共', Object.keys(userData.learningData).length, '条记录');
              storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, userData.learningData);
            }
            
            if (userData.userSettings && typeof userData.userSettings === 'object') {
              console.log('获取到云数据库中的userSettings，共', Object.keys(userData.userSettings).length, '条记录');
              storageManager.setStorage(storageManager.STORAGE_KEYS.USER_SETTINGS, userData.userSettings);
            }
            
            if (userData.todayTaskData && typeof userData.todayTaskData === 'object') {
              console.log('获取到云数据库中的todayTaskData，共', Object.keys(userData.todayTaskData).length, '条记录');
              storageManager.setStorage(storageManager.STORAGE_KEYS.TODAY_TASK_DATA, userData.todayTaskData);
            }
            
            if (userData.userChallengeStats && typeof userData.userChallengeStats === 'object') {
              console.log('获取到云数据库中的userChallengeStats，共', Object.keys(userData.userChallengeStats).length, '条记录');
              storageManager.setStorage(storageManager.STORAGE_KEYS.USER_CHALLENGE_STATS, userData.userChallengeStats);
            }
            
            // 保存userMagicCoins和userChallengeRecords到本地缓存
            if (userData.userMagicCoins !== undefined) {
              console.log('获取到云数据库中的userMagicCoins:', JSON.stringify(userData.userMagicCoins));
              storageManager.setStorage(storageManager.STORAGE_KEYS.USER_MAGIC_COINS, userData.userMagicCoins);
            }
            
            if (userData.userChallengeRecords && typeof userData.userChallengeRecords === 'object') {
              console.log('获取到云数据库中的userChallengeRecords，共', Object.keys(userData.userChallengeRecords).length, '条记录');
              storageManager.setStorage(storageManager.STORAGE_KEYS.USER_CHALLENGE_RECORDS, userData.userChallengeRecords);
            }
          }
        },
        fail: err => {
          console.error('从云数据库获取学习数据失败', err);
        }
      });
    } else {
      console.log('本地缓存中已有学习数据，共', Object.keys(localData).length, '条记录');
    }
  },
  
  // 获取ChallengeDataManager实例
  getChallengeDataManager() {
    return this.globalData.challengeDataManager;
  },

  // 获取DictationManager实例
  getDictationManager() {
    return this.globalData.dictationManager;
  },
  
  // 获取CloudManager实例
  getCloudManager() {
    return this.globalData.cloudManager;
  },
  
  // 获取StorageManager实例
  getStorageManager() {
    return this.globalData.storageManager;
  },
  
  /**
   * 获取AI管理器实例
   */
  getAiManager() {
    return this.globalData.aiManager;
  },
  
  /**
   * 检查缓存空间是否即将耗尽
   * 委托给storageManager处理
   */
  checkStorageSpace() {
    try {
      const storageManager = this.getStorageManager();
      storageManager.checkStorageSpace();
    } catch (error) {
      console.error('检查缓存空间时发生错误:', error);
    }
  },
  
  /**
   * 清理wordDictionary缓存中的同步字段，但保留原始字段
   * 委托给storageManager处理
   */
  cleanWordDictionarySyncFields() {
    try {
      const storageManager = this.getStorageManager();
      return storageManager.cleanWordDictionarySyncFields();
    } catch (error) {
      console.error('清理单词同步数据时发生错误:', error);
    }
  },

  // 全局数据
  globalData: {
    openid: null,
    userInfo: null,
    learningData: {
      totalWordsLearned: 0,
      learningDays: 0,
      medalsCount: 0,
      lastStudyDate: '',
      consecutiveDays: 0
    },
    userSettings: {
      dailyTimeLimit: 30,
      learningDifficulty: 'easy',
      notificationsEnabled: true,
      soundEnabled: true,
      vibrationEnabled: true
    },
    // 应用配置
    appConfig: {},
    // 工具类实例
    wordDataManager: null,
    wordLearningDataManager: null,
    reviewScheduler: null,
    magicCoinManager: null,
    audioManager: null,
    challengeDataManager: null,
    dictationManager: null,
    cloudManager: null,
    storageManager: null,
    aiManager: null
  }
})
